package com.gemini.main.mmap;

import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * gemini
 * com.gemini.main.mmap.Mmap
 *
 * @author zhanghailin
 */
public class Mmap {

    public static void main(String[] args) {
        CharBuffer charBuffer = CharBuffer.wrap("内存映射测试");

        Path path = Paths.get("mmap.txt");

        try (
                FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        ) {
            MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
            if (mappedByteBuffer != null) {
                mappedByteBuffer.put(Charset.forName("UTF-8").encode(charBuffer));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
